﻿using System;
using System.Linq;
using System.Reflection;

namespace CQRS.Reports.SqlQueryBuilder
{
    public class SqlSelectStatementBuilder : ISqlSelectStatementBuilder
    {
        #region ISqlSelectStatementBuilder Members

        public string CreateSqlSelectStatementFromDto<TDto>()
        {
            return string.Format("{0};", GetSelectString<TDto>());
        }

        public string CreateSqlSelectStatementFromDto<TDto>(QueryCriteria selectCriteria)
            where TDto : Report
        {
            return selectCriteria != null
                       ? string.Format("{0} {1};", GetSelectString<TDto>(), GetWhereString(selectCriteria))
                       : string.Format("{0};", GetSelectString<TDto>());
        }

        #endregion

        private static string GetSelectString<TDto>()
        {
            Type type = typeof (TDto);
            PropertyInfo[] properties = type.GetProperties();
            string tableName = type.Name;

            return string.Format("SELECT {0} FROM {1}",
                                 string.Join(",",
                                             properties.Where(x => ! x.PropertyType.IsGenericType).Select(x => x.Name).
                                                 ToArray()), tableName);
        }


        private static string GetWhereString(QueryCriteria selectCriteria)
        {
            return selectCriteria.IsNotEmpty
                       ? string.Format("WHERE {0}",
                                       string.Join(" AND ", selectCriteria.GenerateQueryString()))
                       : string.Empty;
        }
    }
}